<template>
  <view class="container">
    <view class="avatar">
      <image :src="user.avatar" mode="aspectFill" @tap="updateAvatar" />
      <view class="tips">点击头像更换</view>
    </view>

    <view class="name">
      <view class="title" v-if="!toggleName"
        >昵称：{{ user.nickname }}
        <uni-icons
          @click="toggleName = !toggleName"
          type="right"
          color="#555"
          size="18"
      /></view>
      <uni-easyinput
        v-else
        v-model="newName"
        :focus="true"
        trim="all"
        :clearable="false"
        placeholder="请输入昵称"
        primaryColor="#ffa500"
        @blur="changeName(newName)"
      />
    </view>
    <view class="gender">
      <view class="title">性别：</view>
      <uni-data-checkbox
        mode="tag"
        selectedColor="#ffa500"
        v-model="user.gender"
        :localdata="sex"
        @change="changeGender"
      ></uni-data-checkbox>
    </view>

    <view class="phone">
      <view class="title" v-if="!togglePhone"
        >手机号：{{ user.phone
        }}<uni-icons
          @click="togglePhone = !togglePhone"
          type="right"
          color="#555"
          size="18"
      /></view>
      <uni-easyinput
        v-else
        v-model="newPhone"
        trim="all"
        :clearable="false"
        :focus="true"
        primaryColor="#ffa500"
        placeholder="请输入手机号"
        @blur="changePhone()"
      />
    </view>
  </view>
</template>

<script lang="ts" setup>
import { updateUserInfo } from "@/services";
import { onLoad } from "@dcloudio/uni-app";
import { ref } from "vue";
import { useMemberStore } from "@/stores";

const memberStore = useMemberStore();
onLoad(() => {
  user.value = memberStore.profile;
  newName.value = user.value.nickname;
  newPhone.value = user.value.phone;
});
let user = ref<any>({});
let newName = ref("");
let newPhone = ref("");
let toggleName = ref(false);
let togglePhone = ref(false);
const sex = [
  {
    text: "男",
    value: 0,
  },
  {
    text: "女",
    value: 1,
  },
  {
    text: "未知",
    value: 2,
  },
];

const changeName = async () => {
  if (user.value.nickname === newName.value) {
    toggleName.value = !toggleName.value;
    uni.showToast({
      title: "昵称未修改",
      icon: "none",
    });
    return;
  }
  if (newName.value === "") {
    uni.showToast({
      title: "昵称不能为空",
      icon: "error" || "fail",
    });
  } else {
    let result: any = await updateUserInfo({
      nickname: newName.value,
      userId: user.value.user_id,
    });
    if (result.code == 200) {
      uni.showToast({
        title: "修改成功",
        icon: "success",
      });
      user.value.nickname = newName.value;
      toggleName.value = !toggleName.value;
    } else {
      uni.showToast({
        title: "修改失败",
        icon: "error" || "fail",
      });
    }
  }
};

const changeGender = async () => {
  let result: any = await updateUserInfo({
    gender: user.value.gender,
    userId: user.value.user_id,
  });

  if (result.code == 200) {
    uni.showToast({
      title: "修改成功",
      icon: "success",
    });
  } else {
    uni.showToast({
      title: "修改失败",
      icon: "error",
    });
  }
};
const updateAvatar = () => {
  uni.chooseImage({
    sourceType: ["album"], //从相册选择
    success: (chooseImageRes) => {
      const tempFilePaths = chooseImageRes.tempFilePaths;
      uni.uploadFile({
        url: "https://nodes.kimhiz.asia/api/upload",
        filePath: tempFilePaths[0],
        name: "file",
        header: {
          type: "avatar",
        },
        success: async (res: any) => {
          // 请求成功，处理服务器响应
          const data = JSON.parse(res.data);
          if (data.code == 200) {
            // 如果服务器返回成功，更新预览图片的URL
            let img = data.data[0].replace(/\\/g, "/");
            user.value.avatar = img;
            let result: any = await updateUserInfo({
              avatar: img,
              userId: user.value.user_id,
            });
            if (result.code == 200) {
              uni.showToast({
                title: "修改成功",
                icon: "success",
              });
            } else {
              uni.showToast({
                title: "修改失败",
                icon: "error",
              });
            }
          } else {
            // 服务器返回错误信息

            uni.showToast({
              title: "修改失败",
              icon: "error",
            });
          }
        },
      });
    },
    fail: (err) => {
      // 请求失败，打印错误信息

      uni.showToast({
        title: "修改失败",
        icon: "error",
      });
    },
  });
};
const changePhone = async () => {
  if (user.value.phone === newPhone.value) {
    togglePhone.value = !togglePhone.value;
    uni.showToast({
      title: "手机号未修改",
      icon: "none",
    });
    return;
  }
  if (newPhone.value === "") {
    uni.showToast({
      title: "手机号不能为空",
      icon: "error",
    });
  } else {
    let result: any = await updateUserInfo({
      phone: newPhone.value,
      userId: user.value.user_id,
    });
    if (result.code == 200) {
      uni.showToast({
        title: "修改成功",
        icon: "success",
      });
      user.value.phone = newPhone.value;
      togglePhone.value = !togglePhone.value;
    } else {
      uni.showToast({
        title: "修改失败",
        icon: "error",
      });
    }
  }
};
</script>

<style scoped lang="scss">
.container {
  padding: 20rpx;
  .avatar {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    padding: 10rpx 0;
    margin-bottom: 20rpx;

    image {
      width: 150rpx;
      height: 150rpx;
      border-radius: 50%;
      border: 10rpx solid #eee;
    }
    .tips {
      color: #999;
      padding: 10rpx 0;
      font-size: 18rpx;
    }
  }
  .name,
  .gender,
  .phone {
    background-color: #fff;
    height: 80rpx;
    display: flex;
    align-items: center;
    padding: 0 10rpx;
    border-bottom: 1rpx solid #eee;
    font-size: 26rpx;
    color: #999;
  }
  .name {
    .title {
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
  }
  .phone {
    .title {
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
  }
}
</style>
